package com.android.dongshouzhi.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.dongshouzhi.R;
import com.android.dongshouzhi.utils.ConstantsUrl;
import com.zhy.http.okhttp.cookie.store.PersistentCookieStore;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Cookie;

/**
 * Created by gao on 2017/10/25.
 * 跳转到微信端网页
 */

public class BaseWeb extends Activity {

    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.progress)
    RelativeLayout progress;
    @BindView(R.id.web_nodata)
    TextView nodata;
    private BaseWeb mcontext;
    private String url;
    private PersistentCookieStore cookieStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_baseweb);
        ButterKnife.bind(this);
        mcontext = BaseWeb.this;
        url = getIntent().getStringExtra(ConstantsUrl.INTENT_KEY.MAIN_GROUP_MEMBER_WEB_URL);
        cookieStore = new PersistentCookieStore(mcontext);
        initUI();
    }

    private void initUI() {

        if (url == null || url.equals("")) {
            progress.setVisibility(View.GONE);
            nodata.setVisibility(View.VISIBLE);

        } else {
            /* 设置支持Js,必须设置的,不然网页基本上不能看 */
            WebSettings settings = webView.getSettings();
            settings.setJavaScriptEnabled(true);
            /* 设置缓存模式,我这里使用的默认,不做多讲解 */
            settings.setCacheMode(WebSettings.LOAD_DEFAULT);
            /* 设置为true表示支持使用js打开新的窗口 */
            settings.setJavaScriptCanOpenWindowsAutomatically(true);
            /* 大部分网页需要自己保存一些数据,这个时候就的设置下面这个属性 */
            settings.setDomStorageEnabled(true);
            webView.setWebViewClient(new MyWebViewClient());
            webView.setWebChromeClient(new WebChromeClient() {
                @Override
                public void onProgressChanged(WebView view, int newProgress) {
                    super.onProgressChanged(view, newProgress);
                    if (newProgress == 100) {
                        progress.setVisibility(View.GONE);
                    }
                }
            });
            nodata.setVisibility(View.GONE);
            synCookies(mcontext, url);
            webView.loadUrl(url);
        }


    }

    //cookie同步
    @SuppressWarnings("deprecation")
    public void synCookies(Context context, String url) {
        CookieSyncManager.createInstance(context);
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.setAcceptCookie(true);
//      cookieManager.removeSessionCookie();// 移除

        cookieManager.removeAllCookie();
        //   String[] cookie = mCookieStr.split(";");

        //     Cookie[] cookie  = CookieUtil.getCookies().toArray(
// new Cookie[CookieUtil.getCookies().size()]);

        List<Cookie> cookies = cookieStore.getCookies();

        StringBuffer sb = new StringBuffer();


        for (Cookie cookie : cookies) {

            String cookieName = cookie.name();
            String cookieValue = cookie.value();
            if (!TextUtils.isEmpty(cookieName)
                    && !TextUtils.isEmpty(cookieValue)) {
                sb.append(cookieName + "=");
                sb.append(cookieValue + ";");
            }
        }


        String[] cookie = sb.toString().split(";");
        for (int i = 0; i < cookie.length; i++) {
            Log.d("cookie[i]", cookie[i]);
            cookieManager.setCookie(url, cookie[i]);// cookies是在HttpClient中获得的cookie
        }


        CookieSyncManager.getInstance().sync();
    }

    class MyWebViewClient extends WebViewClient {
        //拦截网址
    }

//    @Override
//    public boolean onKeyDown(int keyCode, KeyEvent event) {
//        if (keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()) {
//            String backUrl = webView.getUrl();
//            if (backUrl.equals("") || backUrl.equals(url)) {
//                super.onBackPressed();
//            } else {
//                webView.goBack();
//            }
//            return true;
//        }
//        return super.onKeyDown(keyCode, event);
//    }
}
